package com.lazydong.apiforward.client.gui.pages.userproxy;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lazydong.apiforward.client.framework.PageAbility;
import com.lazydong.apiforward.client.framework.PageInfo;
import com.lazydong.apiforward.client.framework.annotation.ChildPage;
import com.lazydong.apiforward.client.global.GlobalData;
import com.lazydong.apiforward.client.gui.enums.PageInfoEnum;
import com.lazydong.apiforward.client.gui.util.DomainUtil;
import com.lazydong.gui.layout.Margin;
import com.lazydong.gui.layout.Size;
import com.lazydong.gui.layout.linear.HLinearAlign;
import com.lazydong.gui.layout.linear.LinearLayoutUtil;
import com.lazydong.gui.layout.linear.VLinearAlign;

import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@ChildPage
public class UserProxyPage extends PageAbility<Object> {
    private static final Map<String, UserProxy> userProxyMap = new LinkedHashMap<>();

    private static final ButtonGroup group = new ButtonGroup();

    private JPanel showTokenPanel;

    @Override
    public PageInfo getPageInfoEnum() {
        return PageInfoEnum.USER_PROXY;
    }

    @Override
    public int getOrder() {
        return 2;
    }

    @Override
    public void initConfig() {
        String runDataPath = PageInfoEnum.USER_PROXY.runDataPath();
        if (FileUtil.exist(runDataPath)) {
            return;
        }
        List<UserProxy> userProxies = new ArrayList<>();
        UserProxy def = new UserProxy();
        def.login = "";
        def.name = "默认";
        def.token = "";
        userProxies.add(def);
        FileUtil.writeString(JSONUtil.toJsonPrettyStr(userProxies), runDataPath, StandardCharsets.UTF_8);
    }

    @Override
    public Object loadConfig() {
        String json = FileUtil.readString(PageInfoEnum.USER_PROXY.runDataPath(), StandardCharsets.UTF_8);
        List<UserProxy> list = JSONUtil.toList(json, UserProxy.class);
        if (!list.isEmpty()) {
            for (UserProxy userProxy : list) {
                userProxyMap.put(userProxy.login, userProxy);
            }
        }
        return null;
    }

    @Override
    public void buildPage(JPanel parentJPanel, Object config) {
        LinearLayoutUtil.setVLayout(parentJPanel, VLinearAlign.Centre);
        JPanel one = new JPanel();
        LinearLayoutUtil.addComponent(parentJPanel, one, Size.ofRatio(100, 88));
        showTokenPanel = one;
        addOne();

        JPanel two = new JPanel();
        LinearLayoutUtil.addComponent(parentJPanel, two, Size.ofRatio(100, 4));
        addTwo(two);
    }

    private void addOne() {
        ItemListener itemListener = new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (ItemEvent.SELECTED != e.getStateChange()) {
                    return;
                }
                JRadioButton item = (JRadioButton) e.getItem();
                String actionCommand = item.getActionCommand();
                if (StrUtil.isBlank(actionCommand)) {
                    GlobalData.USER_PROXY.set(null);
                    return;
                }
                UserProxy userProxy = userProxyMap.get(actionCommand);
                GlobalData.USER_PROXY.set(userProxy);
            }
        };
        LinearLayoutUtil.setVLayout(showTokenPanel, VLinearAlign.Left);
        for (UserProxy userProxy : userProxyMap.values()) {
            JRadioButton radioButton = new JRadioButton(userProxy.name);
            radioButton.setActionCommand(userProxy.login);
            radioButton.addItemListener(itemListener);
            group.add(radioButton);
            LinearLayoutUtil.addComponent(showTokenPanel, radioButton, Size.ofRatio(50, 4));
        }
    }

    private void addTwo(JPanel two) {
        LinearLayoutUtil.setHLayout(two, HLinearAlign.Centre);
        JLabel name = new JLabel("姓名");
        LinearLayoutUtil.addComponent(two, name, Size.ofRatio(5, 90), Margin.ofLeftRatio(2));
        JTextField nameField = new JTextField();
        LinearLayoutUtil.addComponent(two, nameField, Size.ofRatio(28, 90));

        JLabel login = new JLabel("工号");
        LinearLayoutUtil.addComponent(two, login, Size.ofRatio(5, 90), Margin.ofLeftRatio(4));
        JTextField loginField = new JTextField();
        LinearLayoutUtil.addComponent(two, loginField, Size.ofRatio(35, 90));

        JButton addProxy = new JButton("添加");
        addProxy.addActionListener(e -> addProxyUser(nameField, loginField));
        LinearLayoutUtil.addComponent(two, addProxy, Size.ofRatio(15, 90), Margin.ofLeftRatio(4));
    }

    private void addProxyUser(JTextField nameField, JTextField loginField) {
        String nameText = nameField.getText();
        String loginText = loginField.getText();
        if (userProxyMap.containsKey(loginText)) {
            JOptionPane.showMessageDialog(GlobalData.GLOBAL_FRAME.get(), "sss", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        JSONObject body = new JSONObject();
        body.set("logins", List.of(loginText));
        String post = HttpUtil.post(DomainUtil.serverDomain + UserProxyPageConfig.getTokenUrl, body.toStringPretty());
        List<UserProxy> list = JSONUtil.toList(post, UserProxy.class);
        Map<String, UserProxy> userProxyMap = list.stream().collect(Collectors.toMap(UserProxy::getLogin, temp -> temp));
        UserProxy userProxy = userProxyMap.get(loginText);
        if (userProxy == null) {
            JOptionPane.showMessageDialog(GlobalData.GLOBAL_FRAME.get(), "Token获取异常", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        UserProxy proxy = new UserProxy();
        proxy.name = nameText;
        proxy.login = loginText;
        proxy.token = userProxy.token;
        userProxyMap.put(proxy.login, proxy);

        userProxyMap.put(loginText, proxy);
        ThreadUtil.execAsync(() -> {
            JRadioButton radioButton = new JRadioButton(proxy.name);
            radioButton.setActionCommand(proxy.login);
            group.add(radioButton);
            LinearLayoutUtil.addComponent(showTokenPanel, radioButton, Size.ofRatio(50, 4));
            showTokenPanel.revalidate();
            showTokenPanel.repaint();
        });
    }
}
